package com.baidu.camera.ui;

import android.graphics.Bitmap;
import android.hardware.display.DisplayManager;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.baidu.camera.R;
import com.baidu.camera.utils.FileUtils;
import com.baidu.camera.utils.MetricsUtils;
import com.baidu.camera.utils.ToastUtils;
import com.baidu.camera.widget.CaptureImageView;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.serenegiant.usb.CameraDialog;
import com.serenegiant.usb.DeviceFilter;
import com.serenegiant.usb.USBMonitor;

import org.androidannotations.annotations.EActivity;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.List;

@EActivity
public class USBCamera2Activity extends AppCompatActivity implements View.OnClickListener {
    private View view;

    private String TAG = "USBCameraActivity";
    //devices related
    private USBMonitor usbMonitor;
    private List<DeviceFilter> mFilter;
    private GoogleApiClient mGoogleApiClient;

    private SurfaceView uvcView;


    private int mWidth = 200;
    private int mHeight = 200;
    private com.baidu.camera.widget.CaptureImageView surface;
    private android.widget.Button submit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usbcamera2);
        this.surface = (CaptureImageView) findViewById(R.id.surface);
        initView();
    }

    private void initView() {
        buildGoogleApiClient();
        //init controls
        this.surface = (CaptureImageView) findViewById(R.id.surface);
        this.submit = (Button) findViewById(R.id.submit);
        this.submit.setOnClickListener(this);
        //init usb monitor for finding usb devices
        usbMonitor = new USBMonitor(this, mOnDeviceConnectListener);//init usb monitor
        usbMonitor.register();
        mFilter = DeviceFilter.getDeviceFilters(this, R.xml.device_filter);

        launchCamera();
    }

    private void launchCamera() {
        if (surface == null) return;
        if (!usbMonitor.isRegistered()) return;
        //Try to start camera
        final List<UsbDevice> list = usbMonitor.getDeviceList(mFilter.get(0));
        if (list.size() > 0) {
            UsbDevice device = list.get(0);
            ToastUtils.simpleToast(getApplicationContext(), device.getDeviceName());
            if (usbMonitor.hasPermission(device)) {

                USBMonitor.UsbControlBlock ctrlBlock = new USBMonitor.UsbControlBlock(usbMonitor, device);
                surface.initCamera(ctrlBlock);
                surface.bindCamera();
            } else {
                usbMonitor.requestPermission(device);
            }
        } else {
            CameraDialog.showDialog(USBCamera2Activity.this);
        }
    }

    @Override
    protected void onPause() {
        usbMonitor.unregister();//unregister
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        usbMonitor.destroy();
        super.onDestroy();
    }

    //devices conn listener
    private final USBMonitor.OnDeviceConnectListener mOnDeviceConnectListener = new USBMonitor.OnDeviceConnectListener() {
        @Override
        public void onAttach(final UsbDevice device) {
            Toast.makeText(USBCamera2Activity.this, R.string.usbattached, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onConnect(final UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock, final boolean createNew) {
            surface.initCamera(ctrlBlock);
            surface.bindCamera();
        }

        @Override
        public void onDisconnect(final UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock) {
            surface.releaseCamera();
        }

        @Override
        public void onDettach(final UsbDevice device) {
            Toast.makeText(USBCamera2Activity.this, R.string.usbdetached, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel() {
        }
    };

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApiIfAvailable(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onClick(View v) {
//        view = getWindow().getDecorView();
//        DisplayMetrics metrics = MetricsUtils.winMetrics(this);
//        view.layout(0, 0, metrics.widthPixels, metrics.heightPixels);
//        view.setDrawingCacheEnabled(true);
//        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
//        surface.setDrawingCacheEnabled(true);
//        Bitmap bitmap = Bitmap.createBitmap(surface.getDrawingCache());
//
//        if (bitmap == null) return;
//        try {
//            OutputStream os = new FileOutputStream(FileUtils.createImageFile(Environment.getExternalStorageDirectory() + "/img"));
//            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
//            os.flush();
//            ToastUtils.simpleToast(this, "store successfully");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        //surface.storeBitmap();
    }
}
